package base

import (
	"gitee.com/slion/helper"
	rotatelogs "github.com/lestrrat/go-file-rotatelogs"
	"github.com/sirupsen/logrus"
	prefixed "github.com/x-cray/logrus-prefixed-formatter"
	"log"
	"os"
	"time"
)

// 日志输出到文件
var loggerWriter *rotatelogs.RotateLogs

func LoggerWriter() *rotatelogs.RotateLogs{
	return loggerWriter
}

func init(){
	// 定义日志格式(文本格式)
	// formatter := &logrus.TextFormatter{}

	// 第三方依赖包
	formatter := &prefixed.TextFormatter{}
	logrus.SetFormatter(formatter)

	// 日志级别
	level := os.Getenv("log.level")
	if level == "debug"{
		logrus.SetLevel(logrus.DebugLevel)
	}

	// 控制台高亮显示
	formatter.ForceColors = true
	formatter.DisableColors = false

	// 显示时间戳
	formatter.FullTimestamp = true
	formatter.TimestampFormat = helper.TimestampMillFormat

	// 强制格式化
	formatter.ForceFormatting = true

	// 自定义日志颜色
	formatter.SetColorScheme(&prefixed.ColorScheme{
		InfoLevelStyle:  "green",
		WarnLevelStyle:  "yellow",
		ErrorLevelStyle: "red",
		FatalLevelStyle: "red",
		DebugLevelStyle: "blue",
		TimestampStyle:  "37",
	})

	/*
	logrus.Trace("test")
	logrus.Debug("test")
	logrus.Info("test")
	logrus.Warn("test")
	logrus.Error("test")
	 */

	// 日志文件和滚动配置
	rotate, err := rotatelogs.New(
		"./logs/%Y%m%d.log",
		rotatelogs.WithMaxAge(7 * 24 * time.Hour), // 清除旧日志的时间
		rotatelogs.WithRotationTime(24 * time.Hour), // 日志切割时长
	)
	if err != nil {
		log.Printf("failed to create rotatelogs: %s", err)
	} else {
		loggerWriter = rotate
		// 内容记录到日志里
		// rotate.Write([]byte("小狮子"))
	}
}